<?php
/**
 * Created by PhpStorm.
 * Author: 黑瞎子
 * Date: 2018/4/5
 * Time: 9:27
 */

namespace app\api\service;


use think\Exception;

class WxMessage
{
    //定义微信模板消息的参数

    //发送模板消息的url
    private $sendUrl =
        'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s';
    private $touser; //目标用户
    private $color = 'black';  //不让子类控制颜色

    protected $tpID;  //模板ID
    protected $page;  //点击模板后跳转到小程序的页面
    protected $formID;  //表单提交场景
    protected $data;    //模板内容
    protected $emphasisKeyword; //模板需要放大的关键词

    function __construct()
    {
        $accessToken = new AccessToken();
        $token = $accessToken->get();
        $this->sendUrl = sprintf($this->sendUrl, $token);
    }

    // 开发工具中啦起支付返回的prepay_id是无效的，需要在真机上拉起支付
    // 发送微信模板消息
    protected function sendMessage($openID){
        $data = [
            'touser' => $this->touser,
            'template_id' => $this->tpID,
            'page' => $this->page,
            'form_id' => $this->formID,
            'data' => $this->data,
            'emphasis_keyword' => $this->emphasisKeyword
        ];

        $result = curl_post($this->sendUrl, $data);
        $result = json_decode($result, true);
        if ($result['errcode'] == 0 ){
            return true;
        }else{
            throw new Exception('模板消息发送失败,'. $result['errmsg']);
        }
    }
}